﻿using Shared.DataBaseConfig;
using Shared.SqlAuditHelper;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace QuickFramework.SqlSugarOrm
{
    /// <summary>
    /// 数据库工厂
    /// </summary>
    public static class DbFactory
    {
        static DbFactory()
        {
            // Dapper 使用单数表名
            //SqlMapperExtensions.TableNameMapper = type => type.Name;
        }
        /// <summary>
        /// 根据配置获取数据库类型
        /// </summary>
        /// <param name="databaseType"></param>
        /// <returns></returns>
        private static DbType GetDatabaseType(string databaseType)
        {
            switch (databaseType.ToUpper())
            {
                case "MYSQL":
                    return DbType.MySql;
                case "MSSQLSERVER":
                case "SQLSERVER":
                case "MSSQL":
                case "SQL":
                    return DbType.SqlServer;
                case "ORACLE":
                    return DbType.Oracle;
                case "SQLITE":
                    return DbType.Sqlite;
                case "POSTGRESQL":
                    return DbType.PostgreSQL;
                default:
                    throw new Exception("unsupport database type");
            }
        }
        /// <summary>
        /// 创建数据库连接
        /// </summary>
        /// <returns></returns>
        public static ISqlSugarClient CreateSqlSugarClient(string connectionStringName, bool isMaster = true)
        {
            DBConnection dBConnection = Shared.DataBaseConfig
                                              .DBConnectionManage
                                              .Instance
                                              .DBConnectionConfig
                                              .GetConnection(connectionStringName);

            string connectionStr = dBConnection.GetConnectionString(isMaster);
            if (string.IsNullOrEmpty(connectionStr))
            {
                connectionStr = dBConnection.GetConnectionString();
            }
            ConnectionConfig connectionConfig = new ConnectionConfig()
            {
                ConnectionString = connectionStr,
                DbType = GetDatabaseType(dBConnection.DatabaseType),
                IsAutoCloseConnection = true, //自动释放数据务，如果存在事务，在事务结束后释放
                InitKeyType = InitKeyType.Attribute, //从实体特性中读取主键自增列信息
                //SlaveConnectionConfigs = new List<SlaveConnectionConfig>() //从连接
            };
            if (!isMaster && (dBConnection.Slave?.Count ?? 0) > 0)
            {
                var slaveList = new List<SlaveConnectionConfig>();
                dBConnection.Slave.ForEach(t =>
                {
                    if (!string.IsNullOrEmpty(t.ConnectionString))
                    {
                        var slave = new SlaveConnectionConfig
                        {
                            HitRate = t.Weight,
                            ConnectionString = t.ConnectionString
                        };
                        slaveList.Add(slave);
                    }
                });
                if (null != slaveList && slaveList.Count > 0)
                {
                    connectionConfig.SlaveConnectionConfigs = slaveList;
                }
            }
            var db = new SqlSugarClient(connectionConfig);
            if (dBConnection.SqlAudit)
            {
                db.SqlAudit();
            }
            return db;
        }
    }
}
